﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AddressBook.DAO;
using AddressBook.Entity;
using System.Data.SqlClient;
using System.Text;
using System.Data;

/// <summary>
///SynDataService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。 
// [System.Web.Script.Services.ScriptService]
public class SynDataService : System.Web.Services.WebService
{

    public SynDataService()
    {
        //如果使用设计的组件，请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public bool SynEmployeesDepts(DataTable employees, DataTable depts, string deptids)
    {
        bool isSuccess = true;
        using (SqlConnection con = new SqlConnection(Globle.ConnectionString))
        {
            StringBuilder sqlstr = new StringBuilder();
            try
            {
                string host = Context.Request.UserHostName;

                SqlCommand cmd = new SqlCommand();
                con.Open();
                cmd.Connection = con;
                sqlstr.AppendFormat(" delete from Base_Employee where left(DeptID,4) in ({0})", deptids);
                cmd.CommandText = sqlstr.ToString();
                cmd.ExecuteNonQuery();

                sqlstr.Clear();
                sqlstr.AppendFormat(" delete from Base_Dept where left(DeptID,4) in ({0})", deptids);
                cmd.CommandText = sqlstr.ToString();
                cmd.ExecuteNonQuery();

                SqlBulkCopy copy = new SqlBulkCopy(con);
                copy.DestinationTableName = "Base_Employee";
                copy.BatchSize = 5000;
                foreach (DataRow dr in employees.Rows)
                {
                    dr["FromServices"] = host;
                }
                foreach (DataColumn employ in employees.Columns)
                {
                    copy.ColumnMappings.Add(employ.ColumnName, employ.ColumnName);
                }
                copy.WriteToServer(employees);


                copy.ColumnMappings.Clear();
                copy.DestinationTableName = "Base_Dept";
                foreach (DataColumn dept in depts.Columns)
                {
                    copy.ColumnMappings.Add(dept.ColumnName, dept.ColumnName);
                }
                copy.WriteToServer(depts);
                copy.Close();
            }
            catch (Exception ex)
            {
                isSuccess = false;
            }
        }

        return isSuccess;
    }

}
